package com.woniu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.been.entity.TMenu;
import com.woniu.been.entity.Teachers;
import com.woniu.been.entity.vo.TMenuVo;
import com.woniu.mapper.TMenuMapper;
import com.woniu.service.TMenuService;
import com.woniu.utils.PageResult;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class TMenuServiceImpl implements TMenuService {
    @Autowired
    private TMenuMapper tMenuMapper;

    /*
    * 根据教师名称查询相关菜单
    * */
    @Override
    public List<TMenu> findMenus(String teacherName) {
        List<TMenu> menus = tMenuMapper.findMenus(teacherName);
        //创建一个集合 用来存放一级菜单
        List<TMenu> oneMenus = new ArrayList<TMenu>();
        for (TMenu menu : menus) {
            if (menu.getPid() == 0) {
                oneMenus.add(menu);
            }
        }
        for (TMenu oneMenu : oneMenus) {
            //创建一个集合 用来存放二级菜单
            List<TMenu> twoMenus = new ArrayList<>();
            for (TMenu menu : menus) {
                if (menu.getPid() == oneMenu.getId()) {
                    twoMenus.add(menu);
                }
            }
            oneMenu.setChildren(twoMenus);
        }
        return oneMenus;
    }

    @Override
    public PageResult findAllMenus(TMenuVo tMenuVo, Integer pageNum, Integer pageSize) {
        //设置当前页和每页记录数
        PageHelper.startPage(pageNum,pageSize);
        //调用mapper方法
        List<TMenuVo> list = tMenuMapper.findAllMenus(tMenuVo);
        //创建PageInfo对象
        PageInfo<TMenuVo> pageInfo = new PageInfo<>(list);
        //封装响应数据
        PageResult ps = new PageResult(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getList());
        return ps;
    }

    @Override
    @Transactional
    public void insertMenu(TMenu tMenu) {
        tMenuMapper.insertMenu(tMenu);
        //添加完成菜单之后查找它的id
        List<TMenu> list = tMenuMapper.selectMenuId(tMenu.getTitle());
        //获取集合的最后一个元素的id
        int id = list.get(list.size()-1).getId();
        //添加角色菜单关系表中的数据
        Integer role = tMenu.getRole();
        if(role == 1){
            tMenuMapper.insertRoleMenu(role,id);
        }else if(role == 2){
            tMenuMapper.insertRoleMenu(1,id);
            tMenuMapper.insertRoleMenu(role,id);
        }
    }

    @Override
    public void editMenu(TMenu tMenu) {
        tMenuMapper.editMenu(tMenu);
    }

    @Override
    @Transactional
    public void deleteMenu(Integer id) {
        //删除菜单
        tMenuMapper.deleteMenu(id);
        //删除角色菜单关系表中的数据
        tMenuMapper.deleteRoleMenu(id);
    }
}
